<!--
    参数 ：
    uploadParam     Object  请求参数
    isInit           Boolean   初始化请求 必需
-->

<style lang="less" scoped="scoped">
@import "fileOperation.less";
</style>
<template>
    <Row type="flex" justify="center">
        <Col span="5" class="tree">
            <fieldset>
                <legend>
                    <strong>资料列表</strong>
                </legend>
                <Tree :data="treeData" ref="tree" @on-select-change="selectTree" :render="renderContent" class="demo-tree-render"></Tree>
            </fieldset>
        </Col>
        <Col span="18">
            <fieldset>
                <legend>
                    <strong>资料内容</strong>
                </legend>
                <!-- 文件操作按钮 -->
                <div>
                    <Select
                        v-model="updateClassify"
                        placeholder="请选择"
                        filterable
                        clearable
                        @on-change="changeSelect"
                        style="width: 200px;float:left;"
                    >
                        <Option v-for="(item,index) in classifyArray" :value="item.id" :key="index">{{ item.title }}</Option>
                    </Select>
                    <Button type="primary" icon="md-refresh" @click="updateFile">附件归类</Button>
                    <Button type="warning" icon="ios-cloud-download-outline" @click="downloadFile">附件下载</Button>
                    <Button type="success" icon="ios-search" @click="viewFile">附件预览</Button>
                    <Button type="error" @click="deleteFile" icon="md-trash">附件删除</Button>
                    <!--<LeaseFileUpload @afterUpload="messageUpload" @deleteFile="deleteFile" style="float:left;"></LeaseFileUpload>-->
                    <label class="selectFile">
                        <input type="checkbox" v-model="checked" @click="checkedAll" style="display:none;" />选择(全选/反选)
                    </label>
                </div>
                <div id="watermark_bg" class="pr">
                    <div class="showImgList">
                        <template v-for="(item,index) in checkboxList">
                            <div class="imgCheckList" :key="index" v-show="!item.isDel">
                                <div class="img">
                                    <img :src="item.thumSrc" />
                                </div>
                                <div class="iconType">
                                    <Icon v-if="item.fileStatus === 'standard'" type="ios-checkmark-circle-outline" color="green" size="30" />
                                    <Icon v-else type="ios-close-circle-outline" color="red" size="30" />
                                </div>
                                <div class="title">
                                    <input type="checkbox" v-model="checkedList" :value="item.id" />
                                    <span :title="item.fileName">{{item.fileName}}</span>
                                </div>
                            </div>
                        </template>
                    </div>
                    <div class="drapFile" v-show="isUploadShow">
                        <LeaseFileUpload :modal="modal" @afterUpload="messageUpload" @deleteFile="deleteFile"></LeaseFileUpload>
                    </div>
                </div>
            </fieldset>
        </Col>
        <div v-if="isShowModel">
            <filePreview :showFileList="showFileList" @close-img-model="closeImgModel"></filePreview>
        </div>
    </Row>
</template>
<script>
import Vue from 'vue';
import {
    getUploadList,
    uploadFile,
    saveAttachmentFile,
    showFile,
    updateFile,
    deleteFile,
    downloadFile,
    getBlob,
} from "_p/basic/api/image/image-upload";
import LeaseFileUpload from '_c/file-upload/index';
import filePreview from "../../filePreview.vue";
import Watermark from '../../../defines/watermark.js'
import getUploadTree from "../../../defines/getUploadTree";

import { getImgBlogUrl } from "_p/basic/api/image/image-getImgBlogUrl";
import { deepClone } from "@/libs/utils/ObjectClone";
import pdfImg from "_p/basic/assets/img/pdf.png";
import { getUri } from "@/libs/tools";

Vue.prototype.getUploadTree = getUploadTree;
export default {
    components: {
        LeaseFileUpload,
        filePreview
    },
    props: {
        uploadParam: {
            type: Object,
            require: true,
        },
        isInit: {
            type: Boolean,
            default: false,
            require: true,
        },
        asyncSaveFile: {
            type: Boolean,
            default: false,
        },
        //接口查询使用，同系统不同服务使用
        path: {
            type: String,
        }
    },
    data() {
        return {
            fileList: 0,
            checkboxList: [],
            checked: false, //全选框
            modal: false,
            checkedList: [],
            showFileList: [], //预览需要展示的部分
            isShowModel: false,//是否展示model

            classifyArray: [],
            updateClassify: "",
            attachmentClass: "",
            attachmentSubClass: "",
            treeData: [],
            selectedFileList: [],
            param: {
            },
            initParam: {},
            applyNo: this.uploadParam.busiNo,
            belongNo: this.uploadParam.belongNo,
            busiType: this.uploadParam.busiType,
            busiData: this.uploadParam.busiData,
            isUploadShow: false,
            maxFileNums: null,
            minFileNums: null,
            saveAttachmentFileList: [],

        }
    },
    watch: { //深度 watcher
        'checkedList': {
            handler: function (val, oldVal) {
                if (val.length === this.checkboxList.length) {
                    this.checked = true;
                } else {
                    this.checked = false;
                }
            },
            deep: true
        },
        isInit(val) {
            console.log('isInit(val)', val);
            if (val) {
                this.init()
            }
        }
    },
    mounted() {
        this.init();
    },
    methods: {
        init() {
            if (this.isInit) {
                this.getTree();
                this.selectTree();
            }
        },
        renderContent(h, { root, node, data }) {
            let starflag = false;
            if (data.needNums > 0 || data.needType == 1) {
                starflag = true;
            }
            if (starflag) {
                return h('span', {
                    style: {
                        display: 'inline-block',
                        width: '100%'
                    }
                }, [
                    h('span', [
                        h('Icon', {
                            props: {
                                type: 'ios-medical'
                            },
                            style: {
                                marginRight: '2px',
                                color: '#FF0000',
                            }
                        }),
                        h('span', data.title)
                    ]),
                ]);
            } else {
                return h('span', {
                    style: {
                        display: 'inline-block',
                        width: '100%'
                    }
                }, [
                    h('span', [
                        h('Icon', {
                            props: {
                                type: 'ios-medical'
                            },
                            style: {
                                marginRight: '2px',
                                color: '#FFFFFF',
                            }
                        }),
                        h('span', data.title)
                    ]),
                ]);
            }
        },
        getTree() {
            // let {busiNo,belongNo,busiType,busiData} = this.uploadParam;
            // let initParam = {busiNo,busiType,busiData,};
            getUploadList(this.uploadParam,this.path).then(res => {
                this.loading = false;
                if (res.code === "0000") {
                    this.treeData = this.getUploadTree(res.data);
                    Array.isArray(this.treeData) && this.treeData.forEach(c => {
                        if (c.attachmentClass === 3) {
                            let obj = { id: c.id, title: c.title };
                            this.classifyArray.push(obj);
                            this.initFlags(c);
                        }
                        if (c.attachmentClass === 2 && c.children && c.children.length > 0) {
                            c.children.forEach(s => {
                                if (s.attachmentClass === 3) {
                                    let obj = { id: s.id, title: s.title };
                                    this.classifyArray.push(obj);
                                    this.initFlags(s);
                                }
                            })
                        }
                        if (c.attachmentClass === 1 && c.children && c.children.length > 0) {
                            c.children.forEach(s => {
                                if (s.attachmentClass === 3) {
                                    let obj = { id: s.id, title: s.title };
                                    this.classifyArray.push(obj);
                                    this.initFlags(s);
                                }
                                if (s.attachmentClass === 2 && s.children && s.children.length > 0) {
                                    s.children.forEach(i => {
                                        if (i.attachmentClass === 3) {
                                            let obj = { id: i.id, title: i.title };
                                            this.classifyArray.push(obj);
                                            this.initFlags(i);
                                        }
                                    })
                                }
                            })
                        }
                    })
                }
            });
        },
        changeSelect() {
            let id = this.updateClassify;
        },
        initWatermark(val) {
            let watermarkEl = document.getElementById('watermark_bg');
            Watermark.set(val, watermarkEl)
        },
        messageUpload(uploadInfo) {
            console.log(uploadInfo, "uploadInfo");
            let selectedNode = this.$refs.tree.getSelectedNodes()[0];
            if (selectedNode) {
                let { busiNo, belongNo } = this.uploadParam; // busiNo == this.applyNo; belongNo == this.belongNo

                let attachmentId = selectedNode.id;
                let attachmentName = selectedNode.title;
                let fileType = uploadInfo.fileType;
                let fileName = uploadInfo.name;
                let fileMd5 = uploadInfo.fileMd5;
                // saveAttachmentFile 文件上传成功后发请求的时间
                if (this.asyncSaveFile) {
                    let list = deepClone(this.saveAttachmentFileList);
                    list.push({ attachmentId, attachmentName, fileType, fileName, fileMd5, applyNo: busiNo, belongNo, fileId: fileMd5, isLocal: true, id: fileMd5 })

                    this.saveAttachmentFileList = list;
                    this.showFile(selectedNode);
                } else {
                    uploadFile(attachmentId, attachmentName, fileType, fileName, fileMd5, busiNo, belongNo,this.path).then(res => {
                        if (res.code === "0000") {
                            this.showFile(selectedNode);
                        }
                    })
                }
            }
        },
        /*
          * formData 数据验证 验证通过后 将数据传回父级处理  (保存/提交/审核 通用)
          * @param {String} funcName 回传给父级的方法 (注意父级需要传方法)
          * @param {Object} [data]   父级带来的数据
          */
        formValidate(funcName, data) {
            console.log('funcName', funcName)
            if (!funcName) return;
            if (this.saveAttachmentFileList.length > 0 || this.fileList) {
                let arr = [], _this = this;
                for (let i = 0; i < this.saveAttachmentFileList.length; i++) {
                    let element = this.saveAttachmentFileList[i];
                    arr.push(saveAttachmentFile(element,this.path))
                }
                Promise.all(arr).then(function (resArr) {
                    _this.$emit(funcName, Object.assign({}, data));
                })
            } else {
                this.$Message.error("文件/图片不通过!");
                this.$emit("closeSpin");
            }
        },
        selectTree() {
            let selectNode = this.$refs.tree.getSelectedNodes()[0];
            if (selectNode) {
                this.initWatermark(selectNode.title);
                this.attachmentClass = selectNode.parent;
                this.updateClassify = selectNode.id;
                this.showFile(selectNode);
            }
        },
        showFile(selectNode) {
            let { busiNo, belongNo } = this.uploadParam;

            showFile(busiNo, belongNo, selectNode).then(res => {
                if (res.code === "0000") {
                    let fileList = res.data.fileList;
                    console.log('this.saveAttachmentFileList', this.saveAttachmentFileList);
                    if (this.asyncSaveFile && this.saveAttachmentFileList.length > 0) {
                        fileList.push(...this.saveAttachmentFileList)
                    }
                    let list = [], dataList = []
                    if (fileList.length > 0) {
                        fileList.forEach((file, index) => {
                            let fileType = file.fileType.toLowerCase();

                            if (file.fileStatus !== "standard") {
                                this.isUploadShow = true;
                            }
                            if (fileType === "jpg" || fileType === 'png' || fileType === 'jpg' || fileType === 'jpeg') {
                                // let url= await getBlob(file.fileId,file.fileName);
                                let url = `${_AFS_PROJECT_CONFIG.apiUri}/${getUri('image')}/upload/getBlob/${fileType}/${file.fileId}`;
                                dataList.push(Object.assign({}, file, { thumSrc: url, imgSrc: url }))
                            } else if (fileType === "pdf") {
                                let url = `${_AFS_PROJECT_CONFIG.apiUri}/${getUri('image')}/upload/getBlob/${fileType}/${file.fileId}`;
                                dataList.push(Object.assign({}, file, { thumSrc: pdfImg, imgSrc: url }))
                            }
                        })
                    } else {
                        this.isUploadShow = true;
                    }

                    console.log('fileList', dataList);
                    this.checkboxList = dataList;
                    this.fileList = dataList.length;
                    if (!isNaN(selectNode.maxFileNums)) {
                        dataList.length >= selectNode.maxFileNums
                            ? this.isUploadShow = false
                            : this.isUploadShow = true
                    }
                }
            })
        },
        initFlags(data) {
            if (data.selected == true) {
                this.initWatermark(data.title);
                this.updateClassify = data.id;
                this.showFile(data);
            }
        },
        updateFile() {
            let filelist = this.updateChecked();
            updateFile(filelist,this.path).then(res => {
                if (res.code === "0000") {
                    this.selectTree();
                    this.checkedList = [];
                }
            });
        },
        collectChecked() {
            console.log(this.checkedList, "_this.checkedList");
            let checkedFiles = [];
            this.checkedList.forEach((id, index) => {
                this.checkboxList.forEach((item, index) => {
                    if (id == item.id) {
                        let type = item.fileType;
                        let imageType = "png,jpg,jpeg,gif,bmp";
                        if (type.indexOf(imageType)) {
                            item.type = "img";
                        } else {
                            item.type = item.fileType;;
                        }
                        item.imageFlow = "";
                        checkedFiles.push(item);
                    }
                })
            })
            return checkedFiles;
        },

        backChecked() {
            console.log(this.checkedList, "_this.checkedList");
            let checkedFiles = [];
            this.checkedList.forEach((id, index) => {
                this.checkboxList.forEach((item, index) => {
                    if (id == item.id) {
                        let type = item.fileType;
                        let imageType = "png,jpg,jpeg,gif,bmp";
                        if (type.indexOf(imageType)) {
                            item.type = "img";
                        } else {
                            item.type = item.fileType;
                        }
                        item.imageFlow = "";
                        item.imageUrl = "";
                        item.thumUrl = "";
                        checkedFiles.push(item);
                    }
                })
            })
            return checkedFiles;
        },

        updateChecked() {
            console.log(this.checkedList, "_this.checkedList");
            let attachmentId = this.updateClassify;
            let checkedFiles = { attachmentId: attachmentId, fileList: [] };
            this.checkedList.forEach((id, index) => {
                this.checkboxList.forEach((item, index) => {
                    if (id == item.id) {
                        let file = { id: "" }
                        file.id = id;
                        checkedFiles.fileList.push(file);
                    }
                })
            })
            return checkedFiles;
        },

        deleteChecked() {
            console.log(this.checkedList, "_this.checkedList");
            let checkedFiles = { fileList: [] };

            this.checkedList.forEach((id, index) => {
                this.checkboxList.forEach((item, idx) => {
                    if (id == item.id && !item.isLocal) {
                        if (item.fileStatus != "standard") {
                            checkedFiles.fileList.push({ id });
                        } else {
                            this.$Message.error("合格的影像件不允许删除！");
                        }
                    }
                })
            })
            // 删除本地照片
            this.delLocalFile();
            return checkedFiles;
        },
        delLocalFile() {
            let list = this.saveAttachmentFileList,
                arr = []
            list.forEach((item, idx) => {
                let f = this.checkedList.find(id => id == item.id);
                if (!f && !item.isLocal) {
                    arr.push(item)
                }
            })
            this.saveAttachmentFileList = arr;
            // this.selectTree();
        },
        viewFile() {
            let filelist = this.collectChecked();
            if (filelist.length > 0) {
                this.showFileList = filelist;
                this.isShowModel = true;
                this.$emit("open-img-model")
            }
        },
        deleteFile() {
            let d = this.deleteChecked();
            if (d.fileList.length > 0) {
                deleteFile(d,this.path).then(res => {
                    if (res.code === "0000") {
                        this.selectTree();
                        this.checkedList = [];
                    }
                });
            } else {
                this.selectTree();
                this.checkedList = [];
            }
        },
        downloadFile() {
            let checkedFiles = { data: [] };
            let selectNode = this.$refs.tree.getSelectedNodes()[0];
            let self = this;
            this.checkedList.forEach((id, index) => {
                this.checkboxList.forEach((item, index) => {
                    if (id == item.id) {
                        let md5Value = item.fileId;
                        let downloadsceneid = selectNode.busiNode;
                        let filename = item.fileName;
                        let isView = "0";//下载
                        let isThumb = "";//不传值表示下载原图
                        let downloadParam = { md5Value: md5Value, downloadsceneid: downloadsceneid, filename: filename, isView: isView, isThumb: isThumb };
                        checkedFiles.data.push(downloadParam);
                    }
                })
            })
            downloadFile(checkedFiles,this.path).then(function (response) {
                if (response.status === 200) {
                    self.afs.downloadFile(response)
                }
            });
        },
        // 选择全选与反选
        checkedAll: function () {
            var _this = this;
            if (_this.checked) { //实现反选
                _this.checkedList = [];
            } else { //实现全选
                _this.checkedList = [];
                _this.checkboxList.forEach(function (item, index) {
                    _this.checkedList.push(item.id);
                });
            }
        },
        closeImgModel(value) {
            this.isShowModel = value;
        },
        getFileList() {
            return this.fileList
        },
    }
}
</script>
<style scoped>
</style>
